package cn.itcast.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * *
 * Created by IntelliJ IDEA.
 * Author: caolei
 * Date: 2018/9/8
 * Time: 10:29
 * *
 */
public class JdbcTest {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/heima44";
            String user = "root";
            String password = "883721";
            //获取连接
            con = DriverManager.getConnection(url, user, password);
            String sql = "select * from tb_user where id = ? ";//这里为什么只查出来 张三 30 1？
            //获取数据库操作对象
            ps = con.prepareStatement(sql);
            //设置参数
            ps.setLong(1, 1);
            rs = ps.executeQuery();
            //处理结果集
            while(rs.next()){
                System.out.println(rs.getString("name"));
                System.out.println(rs.getInt("age"));
                System.out.println(rs.getInt("sex"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //释放资源
            try {
                if (rs!=null) {
                    rs.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (ps!=null) {
                    ps.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (con!=null) {
                    con.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
